package com.sesample.seandroidsample;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.facebook.AppEventsConstants;
import com.facebook.AppEventsLogger;

public class ProductFragment extends Fragment {
  private Product mProduct;
  private int mNumber;

  // Need manipulation with the spinner
  private Spinner mProductNumberSpinner;

  public final static String EXTRA_PRODUCT_ID = "com.example.basic.ProductFragment.product_id";

  public static ProductFragment newInstance(int productId) {
    Bundle args = new Bundle();
    args.putInt(EXTRA_PRODUCT_ID, productId);

    ProductFragment fragment = new ProductFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @TargetApi(11)
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int productId = getArguments().getInt(EXTRA_PRODUCT_ID);
    // Get a default product from the inventory
    Catalogue inventory = Catalogue.getInstance(getActivity());
    mProduct = inventory.getProductById(productId);

    mNumber = 1;

    setHasOptionsMenu(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      if (null != NavUtils.getParentActivityName(getActivity())) {
        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
      }
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_product, container, false);

    TextView productName = (TextView)rootView.findViewById(R.id.product_name);
    productName.setText(mProduct.getName());

    TextView productDescription = (TextView)rootView.findViewById(R.id.product_description);
    productDescription.setText(mProduct.getDescription());

    mProductNumberSpinner = (Spinner)rootView.findViewById(R.id.product_number);
    ArrayAdapter<CharSequence> adapter =
        ArrayAdapter.createFromResource(
            getActivity(),
            R.array.product_number_array,
            android.R.layout.simple_spinner_dropdown_item);

    mProductNumberSpinner.setAdapter(adapter);
    mProductNumberSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parent, View view,
          int pos, long id) {
        mNumber = Integer.parseInt(parent.getItemAtPosition(pos).toString());
      }
      @Override
      public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
      }
    });

    Button button = (Button)rootView.findViewById(R.id.product_cart);
    button.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // Handles add to cart button click
        Product p = mProduct;

        // Fire add to cart event!
        Bundle parameters = new Bundle();
        parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
        parameters.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, p.getCategory());
        parameters.putInt(AppEventsConstants.EVENT_PARAM_CONTENT_ID, p.getId());

        AppEventsLogger logger = AppEventsLogger.newLogger(getActivity());

        logger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_TO_CART,
            p.getPrice() * mNumber,
            parameters);

        // Popup the event information
        FragmentManager fm = getActivity().getSupportFragmentManager();
        String message = "EVENT_NAME_ADDED_TO_CART" + "\n" +
            "valueToSum: " + mNumber * mProduct.getPrice() + "\n" +
            "EVENT_PARAM_CURRENCY: USD" + "\n" +
            "EVENT_PARAM_CONTENT_TYPE: " + p.getCategory() + "\n" +
            "EVENT_PARAM_CONTENT_ID: " + p.getId();
        EventDialogFragment eventDialog = EventDialogFragment.newInstance(message);
        eventDialog.show(fm, "EventDialogFragment");

        // Do the actual add to cart logic
        Cart.getInstance(getActivity()).addToCart(mNumber, p.getId());
        mNumber = 1;
        mProductNumberSpinner.setSelection(0);
      }
    });

    return rootView;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
      if (null != NavUtils.getParentActivityName(getActivity())) {
        NavUtils.navigateUpFromSameTask(getActivity());
      }
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public void onResume() {
    super.onResume();

    Product p = mProduct;

    // Fire view product event!
    Bundle parameters = new Bundle();
    parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
    parameters.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, p.getCategory());
    parameters.putInt(AppEventsConstants.EVENT_PARAM_CONTENT_ID, p.getId());

    AppEventsLogger logger = AppEventsLogger.newLogger(getActivity());

    logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT,
        p.getPrice(),
        parameters);

    // Pop up about this event!
    String message = "EVENT_NAME_VIEWED_CONTENT" + "\n" +
        "valueToSum: " + p.getPrice() + "\n" +
        "EVENT_PARAM_CURRENCY: USD" + "\n" +
        "EVENT_PARAM_CONTENT_TYPE: " + p.getCategory() + "\n" +
        "EVENT_PARAM_CONTENT_ID: " + p.getId();

    FragmentManager fm = getActivity().getSupportFragmentManager();
    EventDialogFragment eventDialog = EventDialogFragment.newInstance(message);
    eventDialog.show(fm, "EventDialogFragment");
  }
}
